package javaagent.jdbc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;

/**
 * @author ：zzs
 * @version : 1.0
 * @date ：Created in 2022/3/12 19:58
 * @description：PrepareStatement代理实现类，获取需要的信息
 */
public class PrepareStatementHandler implements InvocationHandler {
    private final PreparedStatement preparedStatement;

    private final SqlInfo sqlInfo;

    private static final String[] SQL_EXECUTE = new String[]{"executeQuery", "executeUpdate", "execute"};

    public PrepareStatementHandler(PreparedStatement preparedStatement, SqlInfo sqlInfo) {
        this.preparedStatement = preparedStatement;
        this.sqlInfo = sqlInfo;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        boolean is_execute = false;
        for (String s : SQL_EXECUTE) {
            if (s.equals(method.getName())) {
                is_execute = true;
                break;
            }
        }
        Object invoke = null;
        try {
            invoke = method.invoke(preparedStatement, args);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            if (is_execute) {
                JdbcCollects.error(sqlInfo, e);
            }
        } finally {
            if (is_execute) {
                // 执行时间
                JdbcCollects.end(sqlInfo);
            }
        }
        return invoke;
    }
}
